package lt.ntec.danblog.server.core;

import com.google.inject.Inject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import lt.ntec.danblog.server.core.Message.Type;

public class SessionMessageManager implements MessageManager, Serializable {

    @Inject
    private HttpSession session;
    private List<Message> messages;
    protected final static String attrName = "SessionMessageManagerMessage";

    public void addMessage(Message message) {
        loadSessionMessages();
        messages.add(message);
    }

    @Override
    public List<Message> getMessages() {
        loadSessionMessages();
        return messages;
    }

    protected void clear() {
        messages.clear();
    }

    public void setSession(HttpSession session) {
        this.session = session;
        if (session == null) {
            throw new RuntimeException("empty session for set");
        }
        loadSessionMessages();
    }

    @SuppressWarnings("unchecked")
    protected void loadSessionMessages() {
        if (session == null) {
            throw new RuntimeException("session is null");
        }
        if (messages == null) {
            if (session.getAttribute(attrName) == null) {
                session.setAttribute(attrName, new ArrayList<Message>());
            }
            messages = (List<Message>) session.getAttribute(attrName);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Message> getFlushMessages() {
        loadSessionMessages();
        List<Message> msg =
                (List<Message>) ((ArrayList<Message>) getMessages()).clone();
        clear();
        return msg;
    }

    @Override
    public void addMessages(List<Message> messages) {
        loadSessionMessages();
        for (Message message : messages) {
            this.messages.add(message);
        }

    }

    @Override
    public void addMessage(Type type, String content) {
        Message message = new SimpleMessage(type, content);
        addMessage(message);
    }
}
